package com.intretech.tj.start;

import com.intretech.tj.device.DeviceVerticle;
import com.intretech.tj.etc.ETCVerticle;
import com.intretech.tj.gpp.GPPVerticle;
import com.intretech.tj.light.LightVerticle;
import com.intretech.tj.mqtt.MQTTVerticle;
import com.intretech.tj.studio.StudioVerticle;
import com.intretech.tj.tcp.TCPVerticle;
import io.quarkus.runtime.ShutdownEvent;
import io.quarkus.runtime.StartupEvent;
import io.smallrye.mutiny.Multi;
import io.vertx.mutiny.core.Vertx;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.event.Observes;
import jakarta.inject.Inject;
import lombok.extern.slf4j.Slf4j;

import static com.intretech.tj.start.OutLog.ElementStart;

@Slf4j
@ApplicationScoped
public class AppLifecycleBean {
    private final OutLog outLog;

    private final TCPVerticle tcpVerticle;
    private final MQTTVerticle mqttVerticle;

    private final DeviceVerticle deviceVerticle;
    private final LightVerticle lightVerticle;
    private final ETCVerticle etcVerticle;
    private final StudioVerticle studioVerticle;
    private final GPPVerticle gppVerticle;


    @Inject
    public AppLifecycleBean(OutLog outLog, TCPVerticle tcpVerticle, MQTTVerticle mqttVerticle, DeviceVerticle deviceVerticle, LightVerticle lightVerticle, ETCVerticle etcVerticle, StudioVerticle studioVerticle, GPPVerticle gppVerticle) {
        this.outLog = outLog;
        this.tcpVerticle = tcpVerticle;
        this.mqttVerticle = mqttVerticle;
        this.deviceVerticle = deviceVerticle;
        this.lightVerticle = lightVerticle;
        this.etcVerticle = etcVerticle;
        this.studioVerticle = studioVerticle;
        this.gppVerticle = gppVerticle;
    }

    void onStart(@Observes StartupEvent ev) {
        outLog.start();
        Multi.createFrom().items(tcpVerticle, mqttVerticle, deviceVerticle, lightVerticle, etcVerticle, studioVerticle, gppVerticle)
                .onItem().transform(verticle ->
                        Vertx.vertx().deployVerticle(verticle)
                ).subscribe().with(verticleUni -> verticleUni
                        .subscribe()
                        .with(id -> log.info(outLog.getMessage(ElementStart, id))))
        ;
    }

    void onStop(@Observes ShutdownEvent ev) {
        outLog.stop();
    }
}
